﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL.Basis
{
    /// <summary>
    /// 客商信息处理类
    /// </summary>
    public class CustomBLL : PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        List<OperateModel> operList;
        OperateModel oper;
        ReturnResult rsl;
        CuDbHelper cuHelper;
        Tools.TxtLogHelper txt;
        public CustomBLL()
        {
            //数据交互
            cmd = new Commands();
            //当前登录人信息
            userLogin = new LoginInfo();
            cuHelper = new CuDbHelper();
            txt = new Tools.TxtLogHelper();
        }
        /// <summary>
        /// 客商数据同步方法
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncCustom(string dataType, bool isAuto = false)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            try
            {
                string baseCode = "", userCode = "";
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                    userCode = "admin";
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                    userCode = userLogin.UserInfo().userCode;
                }
                rsl = this.SyncCustomData(userCode, baseCode, dataType, isAuto);
                //rsl = this.SyncCuClasss(userCode, baseCode, dataType);
                //if (rsl.Result)
                //{
                //    rsl = this.SyncCustomData(userCode, baseCode, dataType, isAuto);
                //}

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 客户数据同步方法
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="baseCode"></param>
        /// <param name="dataType"></param>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncCustomData(string userCode, string baseCode, string dataType, bool isAuto)
        {
            rsl = new ReturnResult();


            try
            {
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    rsl.Message = "数据库编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                if (dataType == "Cu")//客户
                {
                    //sb.Append("select cCusCode cCode,cCusName cName,cCCCode cType,cCusPPerson cChanager,cCusPhone cPhone,");//客商编码、客商名称、大类编码,专员
                    //sb.Append("cCusOAddress cRecAddress,cCusAddress cAddress,dEndDate cStopDate from Customer ");//停用日期,发货地址，公司地址
                    //sb.Append(" where cCusName not like '%停用%' ");
                    sb.Append("select code,name,TelephoneNo,MobilePhone,CustomerAddress,");//客商编码、客商名称、电话、客户地址
                    sb.Append("disabled from AA_PartnerEntity ");//是否停用
                    sb.Append(" where disabled = 0 ");
                }
                else if (dataType == "Sp")//供应商
                {
                    sb.Append("select cVenCode cCode,cVenName cName,cVCCode cType,'' cChanager,cVenPhone cPhone,");//客商编码、客商名称、大类编码,专员
                    sb.Append("'' cRecAddress,cVenAddress cAddress,dEndDate cStopDate from Vendor ");//停用日期,发货地址，公司地址
                    sb.Append(" where cVenName not like '%停用%' ");
                }
                else
                {
                    rsl.Message = string.Format("该标识码无法识别:{0}", dataType);
                    return rsl;
                }
                if (!isAuto)
                {
                    string value = string.Format("-{0}", Tools.ConfigReader.Reader["SyncInventoDay"]);
                    string qydate = DateTime.Now.AddDays(double.Parse(value)).ToString("yyyy-MM-dd");
                    sb.Append(" and updated>='" + qydate + "'");//修改时间
                }
                var table = cuHelper.getData(sb.ToString(), baseCode);

                sb.Clear();
                sb.Append("select * from fun_Customs_info where dataType='" + dataType + "' and baseCode='" + baseCode + "'");
                var qTable = cmd.GetDataTable(sb.ToString());//数据

                List<OperateModel> list = new List<OperateModel>();
                DbCustomer cus;
                OperateModel oper;

                if (table.Rows.Count > 0)
                {
                    #region 构建数据
                    foreach (DataRow r in table.Rows)
                    {
                        oper = new OperateModel();
                        cus = new DbCustomer();
                        var dr = qTable.Select("cuCode='" + r["code"].ToString().Trim() + "'");
                        cus.isDel = 0;
                        cus.isSync = "Y";
                        cus.cuCode = r["code"].ToString(); //h l j l h b  .Replace(" ","")
                        cus.cuName = r["name"].ToString();
                        //cus.cuType = r["cType"].ToString();
                        cus.baseCode = baseCode;
                        cus.arddress = r["CustomerAddress"].ToString();
                        //cus.recArddress = r["cRecAddress"].ToString();
                        cus.dataType = dataType;
                        cus.phone = r["TelephoneNo"].ToString();
                        if (string.IsNullOrWhiteSpace(r["disabled"].ToString()) || r["disabled"].ToString() == "0")
                        {
                            cus.status = "Y";
                        }
                        else
                        {
                            cus.status = "N";
                        }
                        if (dr.Length < 1)
                        {
                            cus.createtime = getNow();
                            cus.createuser = userCode;
                            oper.Types = OperateModel.OperateType.Add;
                        }
                        else
                        {
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "cuCode,baseCode,dataType";
                        }

                        oper.Data = cus;
                        list.Add(oper);
                    }
                    #endregion
                }
                else
                {
                    rsl.Message = "更新完成(无数据)";
                    rsl.Result = true;
                }
                if (list.Count > 0)
                {
                    if (list.Count <= 1000)
                    {
                        rsl = cmd.MoreUpdate(list);
                    }
                    else
                    {
                        var count = Tools.ConfigReader.Reader["SyncSize"];//读取更新信息条数
                        int pcount = 0;
                        var page = list.Count / int.Parse(count);
                        if (list.Count % int.Parse(count) > 0)
                        {
                            pcount = page + 1;
                        }
                        for (int i = 0; i < pcount; i++)
                        {
                            var qList = list.Skip(i * int.Parse(count)).Take(int.Parse(count)).ToList();
                            rsl = cmd.MoreUpdate(qList);
                            txt.AddLogMsg(string.Format("数据同步更新方法({0}-{2})，更新结果：{1}", i, JsonConvert.SerializeObject(rsl), dataType));
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 客商大类数据同步方法
        /// </summary>
        /// <param name="userCode">人员</param>
        /// <param name="baseCode">账套号</param>
        /// <param name="dataType">数据类型</param>
        /// <returns></returns>
        private ReturnResult SyncCuClasss(string userCode, string baseCode, string dataType)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {

                StringBuilder sb = new StringBuilder();
                if (dataType == "Cu")
                {
                    //sb.Append("select cCusCode cCode,cCusName cName,cCCCode cType,cCusPPerson cChanager,");//客商编码、客商名称、大类编码,专员
                    //sb.Append("cCusOAddress cRecAddress,cCusAddress cAddress,dEndDate cStopDate from Customer ");//停用日期,发货地址，公司地址
                    sb.Append("select cCCCode cCode,cCCName cName,iCCGrade cGrade from CustomerClass");
                }
                else if (dataType == "Sp")
                {
                    sb.Append("select cVCCode cCode,cVCName cName,iVCGrade cGrade from VendorClass");
                }
                else
                {
                    rsl.Message = string.Format("该标识码无法识别:{0}", dataType);
                    return rsl;
                }
                var out_cuTypeTable = cuHelper.getData(sb.ToString(), baseCode);
                sb.Clear();
                sb.Append("select * from fun_CommonTree_info where trType='" + dataType + "'");
                var cuTypeTable = cmd.GetDataTable(sb.ToString());


                var dr = out_cuTypeTable.Select("cGrade =1");//获取第一级菜单
                foreach (DataRow r in dr)
                {
                    oper = new OperateModel();
                    this.createCuClassPar(r, ref oper, cuTypeTable, baseCode, userCode, dataType + "0", dataType);
                    operList.Add(oper);
                    this.CallBackCuClass(out_cuTypeTable, 2, r["cCode"].ToString(), ref operList, cuTypeTable, baseCode, userCode, dataType);
                }
                var qdr = cuTypeTable.Select("trCode='" + dataType + "0" + "'");
                if (qdr.Length < 1)
                {
                    DbCommomTree cTree = new DbCommomTree();
                    if (dataType == "Sp")
                    {
                        cTree.trName = "供应商类";
                    }
                    else
                    {
                        cTree.trName = "客户大类";
                    }
                    cTree.memo = "客商信息";
                    cTree.trType = dataType;
                    cTree.trCode = dataType + "0";
                    cTree.isdel = 0;
                    oper = new OperateModel();
                    oper.Data = cTree;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 创建客户大类参数
        /// </summary>
        /// <param name="r"></param>
        /// <param name="oper"></param>
        /// <param name="qTable"></param>
        /// <param name="baseCode"></param>
        /// <param name="isAuto"></param>
        /// <param name="parentCode"></param>
        private void createCuClassPar(DataRow r, ref OperateModel oper, DataTable qTable, string baseCode, string userCode, string parentCode, string dataType)
        {
            var query = qTable.Select("trCode='" + r["cCode"].ToString() + "' and baseCode='" + baseCode + "'");
            bool isAdd = true;
            if (query.Length > 0)
            {
                isAdd = false;
            }
            DbCommomTree cTree = new DbCommomTree();
            cTree.trName = r["cName"].ToString();
            cTree.trCode = r["cCode"].ToString();
            cTree.isdel = 0;
            cTree.parentCode = parentCode;
            cTree.trType = dataType;
            cTree.baseCode = baseCode;
            if (isAdd)
            {
                #region 只有在添加状态下 下列值才会添加
                cTree.createtime = getNow();
                cTree.createuser = userCode;

                #endregion
                oper.Types = OperateModel.OperateType.Add;
            }
            else
            {
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "trCode,baseCode,trType";
            }
            oper.Data = cTree;
        }
        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="gradeNum"></param>
        /// <param name="cCode"></param>
        /// <param name="list"></param>
        /// <param name="sysTable"></param>
        /// <param name="baseCode"></param>
        /// <param name="isAuto"></param>
        private void CallBackCuClass(DataTable dt, int gradeNum, string cCode, ref List<OperateModel> list, DataTable sysTable, string baseCode, string userCode, string dataType)
        {
            var dr = dt.Select("cCode like '" + cCode + "%' and cGrade=" + gradeNum);
            if (dr.Length > 0)
            {
                OperateModel oper;

                foreach (DataRow r in dr)
                {
                    oper = new OperateModel();
                    createCuClassPar(r, ref oper, sysTable, baseCode, userCode, cCode, dataType);
                    list.Add(oper);
                    CallBackCuClass(dt, gradeNum + 1, r["cCode"].ToString(), ref list, sysTable, baseCode, userCode, dataType);
                }
            }
        }
        /// <summary>
        /// 客商大类导航
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        public ReturnResult TreeClassNavigation(string dataType)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonTree_info where trType='" + dataType + "'");
                sb.Append(" and isdel=0 and baseCode='" + userLogin.UserInfo().baseCode + "' ");
                sb.Append(" or (parentCode is null and trType='" + dataType + "')");
                var table = cmd.GetDataTable(sb.ToString());//获取全部有效菜单信息

                List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
                #region 构建数据
                var fMenu = table.Select("parentCode is null");//获取所有父级菜单
                for (int i = 0; i < fMenu.Length; i++)
                {
                    var fdic = new Dictionary<string, object>();
                    fdic["title"] = string.Format("{0}({1})", fMenu[i]["trName"].ToString(), fMenu[i]["trCode"].ToString());
                    fdic["id"] = fMenu[i]["trCode"].ToString();
                    fdic["spread"] = "true";

                    #region 子菜单
                    List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                    this.ChildUrl(table, fMenu[i]["trCode"].ToString(), ref cList);
                    fdic["children"] = cList;
                    #endregion
                    menuList.Add(fdic);
                }
                #endregion
                rsl.Data = menuList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private void ChildUrl(DataTable table, string cCode, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentCode='" + cCode + "'");
            if (dr.Length > 0)
            {
                for (int x = 0; x < dr.Length; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["title"] = string.Format("{0}({1})", dr[x]["trName"].ToString(), dr[x]["trCode"].ToString());
                    cdic["id"] = dr[x]["trCode"].ToString();
                    ChildUrl(table, dr[x]["trCode"].ToString(), ref tempList);
                    // cdic["spread"] = "true";
                    cdic["children"] = tempList;
                    chlist.Add(cdic);
                }
            }
        }
        /// <summary>
        /// 客商数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getCustomDataList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                //var arr = condition.Split(',').ToList();
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("  isdel=0 and baseCode='" + userLogin.UserInfo().baseCode + "'");
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (obj.Name == "cuType")
                        {
                            sb.Append(" and cuType like '" + json["cuType"].ToString() + "%'");
                        }
                        else if (obj.Name == "dataType" || obj.Name == "status")
                        {
                            sb.Append("  and " + obj.Name + "='" + obj.Value.ToString().Trim() + "'");
                        }
                        else
                        {
                            sb.Append("  and " + obj.Name + " like '%" + obj.Value.ToString().Trim() + "%'");
                        }
                    }
                }
                var list = cmd.PageList("fun_Customs_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                //rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
